package com.lemobar.pay.service.impl.alipay;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.GsonBuilder;
import com.lemobar.pay.constants.AliPayConstants;
import com.lemobar.pay.model.PayRequest;
import com.lemobar.pay.model.PayResponse;
import com.lemobar.pay.model.alipay.AliPayApi;
import com.lemobar.pay.model.alipay.request.AliPayTradeCreateRequest;
import com.lemobar.pay.model.alipay.response.AliPayOrderCreateResponse;
import com.lemobar.pay.model.alipay.response.AliPayTradeCreateResponse;
import com.lemobar.pay.utils.JsonUtil;
import com.lemobar.pay.utils.MapUtil;
import com.lemobar.pay.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 支付宝 H5 支付
 *
 */
@Slf4j
public class AlipayH5ServiceImpl extends AliPayServiceImpl {

	private Retrofit retrofit = new Retrofit.Builder()
			.baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN)
			.addConverterFactory(GsonConverterFactory.create(
					new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
			))
			.client(new OkHttpClient.Builder()
					.addInterceptor((new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)))
					.build()
			).build();


	@Override
	public PayResponse pay(PayRequest request) {
		AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest();
		aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId());
		aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter));
		aliPayOrderQueryRequest.setNotifyUrl(StringUtil.isEmpty(request.getNotifyUrl()) ? aliPayConfig.getNotifyUrl() : request.getNotifyUrl());

		AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent();
		bizContent.setOutTradeNo(request.getOrderId());
		bizContent.setTotalAmount(request.getOrderAmount());
		bizContent.setSubject(request.getOrderName());

		bizContent.setBuyerId(request.getOpenid());


		aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*",""));
		aliPayOrderQueryRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey()));

		Call<AliPayTradeCreateResponse> call = retrofit.create(AliPayApi.class)
				.tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest)));

		Response<AliPayTradeCreateResponse> retrofitResponse  = null;
		try{
			retrofitResponse = call.execute();
		}catch (IOException e) {
			e.printStackTrace();
		}
		assert retrofitResponse != null;
		if (!retrofitResponse.isSuccessful()) {
			throw new RuntimeException("【支付宝创建订单】网络异常. alipay.trade.create");
		}
		AliPayTradeCreateResponse aliPayTradeCreateResponse = retrofitResponse.body();
		assert aliPayTradeCreateResponse != null;
		AliPayTradeCreateResponse.Content response = aliPayTradeCreateResponse.getAlipayTradeCreateResponse();
		/*
		if(!response.getCode().equals(AliPayConstants.RESPONSE_CODE_SUCCESS)) {
			throw new RuntimeException("【支付宝创建订单】alipay.trade.create. code=" + response.getCode() + ", returnMsg=" + response.getMsg() + String.format("|%s|%s", response.getSubCode(), response.getSubMsg()));
		}
		 */

		PayResponse payResponse = new PayResponse();
		payResponse.setResultCode(response.getCode());
		payResponse.setErrCode(response.getSubCode());
		payResponse.setErrCodeDes(response.getSubMsg());
		payResponse.setOutOrderId(response.getTradeNo());
		payResponse.setOrderId(response.getOutTradeNo());
		return payResponse;
	}
}
